import 'dart:convert';

import 'package:flutter/material.dart';
// import 'package:flutter/rendering.dart';
// import 'package:flutter/services.dart';
import 'package:flutter_channel_demo/common/Global.dart';
import 'package:flutter_channel_demo/models/worker.dart';
import 'package:flutter_channel_demo/utils/tools.dart';
import 'package:flutter_channel_demo/widgets/popUp.dart';
// import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../constants/common.dart';
// import '../../models/auth.dart';
// import '../../widgets/popUp.dart';
import 'package:flutter_channel_demo/api/worker.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  // final String mobile;

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  String _status = 'no-action';
  late String? _mobile;
  late String? _password;
  late bool _savePass = true;

  final formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  final TextEditingController _controllerMobile = TextEditingController();
  final TextEditingController _controllerPassword = TextEditingController();

  @override
  initState() {
    // _controllerMobile = TextEditingController(); // text: widget?.mobile ?? ""
    // _controllerPassword = TextEditingController();
    _loadMobile();
    super.initState();
    print(_status);
  }

  // 自动填充mobile
  void _loadMobile() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var saveMobile = prefs.getString("saved_mobile") ?? "";
      var savePassword = prefs.getString("saved_password") ?? "";

      _controllerMobile.text = saveMobile;
      _controllerPassword.text = savePassword;
      // }
    } catch (e) {
      print(e);
    }
  }

  void _changeSwitch(bool val) {
    setState(() {
      _savePass = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    // var _auth = Provider.of<AuthModel>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title: const Text('登录')),
      body: SafeArea(
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          key: const PageStorageKey("Divider 1"),
          children: <Widget>[
            const SizedBox(
              height: 220.0,
              child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Icon(
                    Icons.person,
                    size: 175.0,
                  )),
            ),
            Form(
              key: formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ListTile(
                    title: TextFormField(
                      decoration: const InputDecoration(labelText: '手机号码'),
                      validator: (val) => val!.isEmpty ? '手机号码不能为空' : null,
                      onSaved: (val) => _mobile = val!,
                      obscureText: false,
                      keyboardType: TextInputType.text,
                      controller: _controllerMobile,
                      autocorrect: false,
                    ),
                  ),
                  ListTile(
                    title: TextFormField(
                      decoration: const InputDecoration(labelText: '密码'),
                      validator: (val) => val!.isEmpty ? '密码不能为空' : null,
                      onSaved: (val) => _password = val!,
                      obscureText: true,
                      controller: _controllerPassword,
                      keyboardType: TextInputType.text,
                      autocorrect: false,
                    ),
                  ),
                ],
              ),
            ),
            SwitchListTile(
              activeColor: const Color(0xff334154),
              title: const Text(
                '记住密码',
                textScaleFactor: textScaleFactor,
              ),
              value: _savePass,
              onChanged: (value) => {_changeSwitch(value)},
            ),
            ListTile(
              title: ElevatedButton(
                // style: const ButtonStyle(
                //     backgroundColor:
                //         MaterialStatePropertyAll(Color(0xff334154))),
                child: const Text(
                  '登录',
                  textScaleFactor: textScaleFactor,
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () async {
                  final form = formKey.currentState;
                  if (form!.validate()) {
                    form.save();
                    final snackbar = SnackBar(
                      duration: Duration(seconds: 30),
                      content: Row(
                        // ignore: prefer_const_literals_to_create_immutables
                        children: <Widget>[
                          CircularProgressIndicator(),
                          const Text("  Logging In...")
                        ],
                      ),
                    );
                    // _scaffoldKey.currentState.showSnackBar(snackbar);

                    setState(() => this._status = 'loading');
                    print('登录 => $_mobile, $_password');
                    login(
                      _mobile!.toString().toLowerCase().trim(),
                      _password.toString().trim(),
                      context,
                    ).then((result) {
                      var data = result['data'];

                      if (result['code'] == 20000) {
                        print(data['token']);
                        Global.worker.token = data['token'];
                        Worker worker;
                        SharedPreferences.getInstance().then((prefPre) {
                          prefPre.setString("token", data['token']);
                          // 处理保存账号密码的缓存
                          if (_savePass) {
                            prefPre.setString("saved_mobile", _mobile!);
                            prefPre.setString("saved_password", _password!);
                          } else {
                            prefPre.setString("saved_mobile", "");
                            prefPre.setString("saved_password", "");
                          }

                          getInfo().then((info) {
                            if (info['code'] == 20000) {
                              worker = Worker.fromJson(info['data']);
                              print(worker.toJson());
                              // 全局存一份
                              SharedPreferences.getInstance().then((pref) {
                                pref.setString("token", data['token']);
                                pref.setString(
                                    "worker", jsonEncode(worker.toJson()));
                              });
                            }

                            switchTab(context, '/home');
                          });
                        });
                      } else {
                        setState(() => this._status = 'rejected');
                        showAlertPopup(context, '提示', result['message'], '确定');
                      }
                      // if (!globals.isBioSetup) {
                      //   setState(() {
                      //     print('Bio No Longer Setup');
                      //   });
                      // }
                      // _scaffoldKey.currentState.hideCurrentSnackBar();
                    });
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
